import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "./tools";
export const serverUrl = "http://47.94.144.217:8080";
// import { getToken } from "./tools";

const instance = axios.create({
  baseURL: serverUrl, // 请求的基础地址
  timeout: 5000, // 请求超时时间
});

// Add a request interceptor
// 全局请求拦截，发起网络请求之前执行
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent

    config.headers.token = getToken();
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 全局响应拦截，网络请求返回之后执行
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data

    return response.data;
  },
  function (error) {
    // NProgress.done();
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    if (error.response?.status == 401) {
      window.location.href = "/h5/#/login";
    }
    return Promise.reject(error);
  }
);

/**
 * 发起一个get请求
 * @param {*} url     地址
 * @param {*} params  url中传递的参数
 * @returns
 */
export const get = (url, params) =>
  instance.get(url, {
    params, // 表示url中传递的参数
    headers: {
      Authorization: getToken(),
    },
  });

/**
 * 发起post请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const post = (url, data) => instance.post(url, data);

/**
 * 发起put请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const put = (url, data) => instance.put(url, data);

/**
 * 发起del请求
 * @param {*} url   地址
 * @param {*} params  数据
 * @returns
 */
export const del = (url, params) =>
  instance.delete(url, {
    params, // 表示url中传递的参数
    headers: {
      Authorization: getToken(),
    },
  });

export default instance;
